package com.hnhcyy.goods.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.codec.binary.StringUtils;
import org.apache.commons.lang.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hnhcyy.b2b.common.exception.ExceptionCast;
import com.hnhcyy.b2b.promotion.client.GiveInfoClient;
import com.hnhcyy.b2b.promotion.pojo.Give;
import com.hnhcyy.b2b.promotion.pojo.Givedetail;
import com.hnhcyy.goods.mapper.GoodsMapper;
import com.hnhcyy.goods.mapper.ShoppingcartMapper;
import com.hnhcyy.goods.pojo.Goods;
import com.hnhcyy.goods.pojo.GoodsResultEnum;
import com.hnhcyy.goods.pojo.Shoppingcart;
import com.hnhcyy.goods.service.ShoppingcartService;

@Service
public class ShoppingcartServiceImpl implements ShoppingcartService{

	@Autowired
	private GoodsMapper goodsMapper;
	@Autowired
	private ShoppingcartMapper shoppingcartMapper;
	@Autowired
	private GiveInfoClient giveInfoClient;


	@Override
	public boolean saveItem(String spid, int fqty, int sjid, String dwbh) {
		// 查询商品基本信息
		Goods goods = goodsMapper.selectItemMoreById(spid, null, sjid);
		if(goods == null) {
			return false;
		}
		if(goods.getSpBal() == null ||
				(goods.getSpBal() != null && goods.getSpBal().getPihao() == null)) {
			// 如果缺货，则抛出异常
			ExceptionCast.cast(GoodsResultEnum.GOODS_STOCKOUT);
		}
		// 查询购物车中该商品是否存在
		Shoppingcart shoppingcart = shoppingcartMapper.selectItemById(spid, dwbh, sjid);
		if(shoppingcart == null) {
			shoppingcart = new Shoppingcart();
			shoppingcart.setSpid(spid);
			shoppingcart.setDwbh(dwbh);
			shoppingcart.setSjid(sjid);
			shoppingcart.setPihao(goods.getSpBal().getPihao());
			// 判断拆零价
			double priceChl = goods.getPriceChl();
			if(priceChl > 0 && fqty < goods.getJlgg()){
				// 拆零价大于0，数量小于件装量
				shoppingcart.setFprice(goods.getPriceChl());
			}		
			shoppingcart.setFprice(goods.getPrice());
			shoppingcart.setFqty(fqty);
			return shoppingcartMapper.insertItem(shoppingcart) > 0;
		}else {
			// 如果购物车存在该商品，则更新数量
			shoppingcart.setFqty(fqty + shoppingcart.getFqty());
			return shoppingcartMapper.updateItem(shoppingcart) > 0;
		}
	}

	@Override
	public boolean savePackage(int packageId, int fqty, int sjid, String dwbh) {
		// 调用促销中心，查询套餐信息
		Give give = giveInfoClient.packageOne(packageId);
		if(give == null) {
			ExceptionCast.cast(GoodsResultEnum.PACKAGE_ERROR);
		}
		// 查询购物车中是否有该套餐
		List<Shoppingcart> cartList = shoppingcartMapper.selectListByGivefid(dwbh, sjid, packageId);
		// 套餐中商品详情
		List<Givedetail> givedetailList = give.getGivedetailList();
		int affectRows = 0;
		outer1 : for (Givedetail givedetail : givedetailList) {
			int i = 0;
			if(cartList.isEmpty()) {
				// 新增
				Shoppingcart shoppingcart = new Shoppingcart();
				shoppingcart.setDwbh(dwbh);
				shoppingcart.setSjid(sjid);
				shoppingcart.setGivefid(packageId);
				shoppingcart.setSpid(givedetail.getSpid());
				shoppingcart.setPihao("");
				shoppingcart.setFprice(givedetail.getGoods().getPriceDiscount());
				shoppingcart.setFqty(fqty * givedetail.getFqty());
				i = shoppingcartMapper.insertItem(shoppingcart);
			}else {
				// 修改
				outer2 : for (Shoppingcart cart : cartList) {
					if(StringUtils.equals(cart.getSpid(), givedetail.getSpid())) {
						// 购物车套餐的商品ID和原始套餐的商品ID相同
						cart.setFqty(fqty * givedetail.getFqty() + cart.getFqty());
						i = shoppingcartMapper.updateItem(cart);
						// 更新数量之后跳出该层循环，进入下一个外层循环
						break outer2;
					}
				}
			}
			// 若有一条记录失败，则抛出异常
			if(i == 0) ExceptionCast.cast(GoodsResultEnum.SHOPPINCART_ADD_FAIL);
			affectRows += i;

		};
		return affectRows == givedetailList.size();
	}

	@Override
	public Map<String,Object> getListByDwbh(int sjid, String dwbh) {
		// 获取购物车列表
		List<Shoppingcart> shoppingcartList = shoppingcartMapper.selectListByDwbh(dwbh, sjid);

		Map<String,Object> retMap = new HashMap<>();
		List<Shoppingcart> packageCartList= new ArrayList<>();	// 套餐商品
		List<Shoppingcart> singleCartList= new ArrayList<>();	// 普通商品

		Set<Integer> givefidList = new HashSet<>();	// 记录所有套餐的givefid

		for (Shoppingcart shoppingcart : shoppingcartList) {
			if(shoppingcart.getGivefid() > 0){
				givefidList.add(shoppingcart.getGivefid());
				packageCartList.add(shoppingcart);
			}else{
				singleCartList.add(shoppingcart);
			}
		}
		List<Map<String, Object>> packageList = handlePkgcartList(packageCartList, givefidList);

		retMap.put("singleList", singleCartList);
		retMap.put("packageList", packageList);
		
		return retMap;
	}

	/**
	 * 处理套餐
	 * @author sheyongjun
	 * @date 2019年2月16日
	 */
	private List<Map<String, Object>> handlePkgcartList(List<Shoppingcart> packageCartList, Set<Integer> givefidList) {
		//	构建套餐商品购物车列表的json数据
		List<Map<String,Object>> packageList = new ArrayList<>();
		for (Integer givefid : givefidList) {
			List<Shoppingcart> tmpcartList = new ArrayList<>();
			int pkgqty = 0;	// 套餐商品的数量（套数）
			for(int i = 0; i < packageCartList.size(); i++){
				Shoppingcart pkgCart = packageCartList.get(i);
				if(ObjectUtils.equals(pkgCart.getGivefid(), givefid)){
					// 调用促销中心，查询该套餐中该商品的基本信息
					Givedetail givedetail = giveInfoClient.packageGoods(givefid, pkgCart.getSpid());
					if(givedetail == null) {
						return packageList;
					}
					int pkgBaseQty = givedetail.getFqty();	// 套餐中单个商品的基数
					int fqty = pkgCart.getFqty();	// 购物车实际数量
					// 以下逻辑是规避套餐中商品数量和套数不成比例的问题
					if(i == 0){
						// 套餐数量计算，以套餐中第一个商品为基准
						pkgqty = fqty / pkgBaseQty;
					} else if(i > 0 && fqty != pkgqty * pkgBaseQty){	
						// 从套餐中第二个商品开始，如果计算的套餐数量与上一个不同，则调整购物车套餐单个商品数量
						pkgCart.setFqty(pkgqty * pkgBaseQty);
						shoppingcartMapper.updateItem(pkgCart);
					}
					tmpcartList.add(pkgCart);
				}
			}
			Map<String,Object> map = new HashMap<>();
			map.put("givefid", givefid);
			map.put("pkgqty", pkgqty);
			map.put("shoppingcartList", tmpcartList);
			packageList.add(map);
		}
		return packageList;
	}

	@Override
	public boolean updateItem(Shoppingcart shoppingcart) {
		
		if(shoppingcart.getFid() != null) {
			// 普通商品修改
			return shoppingcartMapper.updateItem(shoppingcart) > 0;
		}else if(shoppingcart.getGivefid() != null) {
			// 套餐商品修改
			// 查询该套餐中的商品
			List<Shoppingcart> cartList = 
					shoppingcartMapper.selectListByGivefid(shoppingcart.getDwbh(), shoppingcart.getSjid(), shoppingcart.getGivefid());
			int affectRows = 0;
			for (Shoppingcart cart : cartList) {
				// 调用促销中心，查询该套餐中该商品的基本信息
				Givedetail givedetail = giveInfoClient.packageGoods(shoppingcart.getGivefid(), cart.getSpid());
				if(givedetail == null) {
					return false;
				}
				cart.setFqty(shoppingcart.getFqty() * givedetail.getFqty());
				int i = shoppingcartMapper.updateItem(cart);
				// 若有一条记录更新失败，则抛出异常
				if(i == 0) ExceptionCast.cast(GoodsResultEnum.SHOPPINCART_UPDATE_FAIL);
				affectRows += i;
			}
			return affectRows == cartList.size();
		}else {
			ExceptionCast.cast(GoodsResultEnum.PARAM_MISSING);
			return false;
		}
	}

	@Override
	public boolean removeItem(int[] fids) {
		int length = fids.length;
		if(fids.length == 1) {
			return shoppingcartMapper.deleteItem(fids[0]) > 0;
		}else {
			for(int i = 0; i < length; i++) {
				try {
					shoppingcartMapper.deleteItem(fids[i]);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			return true;
		}
	}

}
